import React, {useEffect, useRef, useState} from "react";
import {Button, message, Modal, Space, Upload} from "antd";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import styles from './index.module.scss'
import Cropper from "react-cropper";
import {UploadFile} from "antd/es/upload/interface";
import {RcFile} from "antd/lib/upload";

interface UploadImgProps {
  onChange?: (values: any) => void;
  value?: string;
  crop?: boolean;
  accept?: string;
}

const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = error => reject(error);
  });

const UploadImg: React.FC<UploadImgProps> = (props) => {

  const {onChange, value, crop, accept = ".jpg, .jpeg, .png"} = props;

  const cropperRef = useRef<any>();
  const [fileList, setFileList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');

  useEffect(() => {
    if (value) {
      setFileList([
        {
          uid: "-1",
          status: "done",
          url: value,
          percent: 100,
        },
      ]);
    }
  }, [value]);

  const onRemove = () => {
    setFileList([]);
    // setImgUrl("");
    if (onChange) {
      onChange(undefined);
    }
  };

  const handleCancel = () => {
    // setFileList([]);
    // setImgUrl("");
  };

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      console.log('-------------getBase64----------------')
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    setPreviewVisible(true);
  };

  const handleOk = async () => {

  }

  const beforeUpload = (file: any) => {

  }

  const uploadChange = async (options: any) => {
    if (options.fileList.length > 0 && !crop) {
      await doImgUpload(options.file);
    }
  }

  const doImgUpload = async (file: any) => {
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      // message.warning()
      return;
    }
    const imgItem = {
      uid: "1", // 注意，这个uid一定不能少，否则上传失败
      name: file.name,
      status: "uploading",
      percent: 99, // 注意不要写100。100表示上传完成
    };
    setFileList([imgItem]);
    setLoading(true);
    /*   const res = await apiUploadLogo(file, {
         folderPrefix: "static",
       });*/
    setLoading(false);
    /* if (res.code === 0) {
       setFileList([{
         uid: "1",
         name: file.name,
         status: "done",
         url: res.data,
       }]);
       if (onChange) {
         onChange(res.data);
       }
     }*/
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined/> : <PlusOutlined/>}
      <div style={{marginTop: 8}}>{loading ? "上传中" : "上传"}</div>
    </div>
  );

  return (
    <div className={styles.uploadImg}>
      <Space align="start">
        <Space align="center" direction="vertical" size={0}>
          <Upload
            name="file"
            listType="picture-card"
            // className={styles.uploader}
            accept={accept}
            showUploadList={true}
            fileList={fileList}
            onRemove={onRemove}
            beforeUpload={beforeUpload}
            onPreview={handlePreview}
            onChange={uploadChange}
          >
            {fileList.length > 0 ? null : uploadButton}
          </Upload>

          <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={() => setPreviewVisible(false)}>
            <img alt="example" style={{width: '100%'}} src={previewImage}/>
          </Modal>

          {!fileList.length && (
            <div className={styles.tip}>
              {accept === ".ico" ? `支持 ICO 文件` : `支持 JPG/PNG/JPEG 文件`}
            </div>
          )}
        </Space>
        <Button
          size="small"
          type="primary"
          ghost
          // disabled={themeConfigStore.btnLoading}
          // onClick={reset}
        >
          默认
        </Button>
      </Space>

      {crop && (
        <Modal
          title="编辑图片"
          width={900}
          // visible={modalVisible}
          onOk={handleOk}
          onCancel={handleCancel}
          centered
          maskClosable={false}
        >
          <div className={styles.cropper_container}>
            <div className={styles.cropperBox}>
              <Cropper
                src={value}
                name="Cropper"
                ref={cropperRef}
                className={styles.cropper}
                viewMode={1}
                zoomable={false}
                aspectRatio={0} // 这个是设置比例的参数 我这里设置的1:1
                guides={false}
                preview={"." + styles["img-preview"]}
                cropBoxResizable={true}
                autoCropArea={1}
              />
            </div>
            <div>
              <div className={styles.previewBox}>
                <div className={styles["img-preview"]}/>
              </div>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}

export default UploadImg
